package block

import (
	"bytes"
	"errors"
	bolt "github.com/boltdb/github-boltdb-master"
)

/**
 ** @author: hui
 ** @email: 3231954428@qq.com
 ** @phone: 15779563913
 ** @DataTime: 2022/3/18 10:40
 **/

type ChainIterator struct {
	//数据库
	DB				*bolt.DB
	//标志位
	CurrentHash		[]byte
}


/**
用迭代器找区块
 */

func(iterator *ChainIterator) Next() (*Block, error){

	var block *Block
	var err error

	//读取数据库里的内容
	err = iterator.DB.View(func(tx *bolt.Tx) error {

		bucket := tx.Bucket([]byte(BUKET_BLOCK))
		if bucket == nil{
			return errors.New("没有桶1")
		}
		get := bucket.Get(iterator.CurrentHash)

		//反序列化
		block, err = DeSerialize(get)
		if err != nil{
			return err
		}

		//获取上一个区块
		iterator.CurrentHash = block.PrevHash

		return nil

	})


	return block, err
}


/**
判断是否是创世区块
 */

func (iterator *ChainIterator) HasNext() bool{

	compare := bytes.Compare(iterator.CurrentHash, nil)

	//判断compare是否为0
	return compare != 0
}


